'use strict';

const Controller = require('egg').Controller;
const Res = require('../utils/response');
const joi = require("joi")

class CategoryController extends Controller {
  // 显示数据
  async show() {
    const {
      ctx
    } = this;
    const schema = {
      name: joi.string(),
      id: joi.number()
    }
    const {
      error,
      value
    } = joi.validate(ctx.request.query, schema);
    if (error) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '操作失败');
    }
    const result = await ctx.model.Category.findAll({
      where: {
        name: {
          $like: `%${value&&value.name || ''}%`
        },
        id: {
          $like: `%${value&&value.id || ''}%`
        }
      },
      limit: 10,
      offset: 0
    });
    ctx.body = Res(0, result);
  }

  // 创建数据
  async create() {
    const {
      ctx
    } = this;
    // 定义验证规则
    const schema = {
      name: joi.string().required().error(new Error("分类名称格式不正确")),
      desc: joi.string().error(new Error("介绍格式不正确")),
      cover: joi.string().error(new Error("图片路径有误"))
    }

    const {
      error,
      value
    } = joi.validate(ctx.request.body, schema);
    if (error) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '操作失败');
    }
    const result = await ctx.model.Category.create(value);
    ctx.body = Res(0, result);
  }

  // 更新分类
  async update() {
    const ctx = this.ctx;
    const schema = {
      name: joi.string(),
      desc: joi.string(),
      cover: joi.string(),
      id: joi.number().required(),
    }

    const {
      error,
      value
    } = joi.validate(ctx.request.body, schema);
    if (error) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '操作失败');
    }

    const item = await ctx.model.Category.findByPk(value.id);
    if (!item) {
      ctx.status = 404;
      return;
    }

    await item.update(value);
    ctx.body = Res(0, item);
  }

  // 删除
  async destroy() {
    const ctx = this.ctx;
    const schema = {
      id: joi.number().required(),
    }
    const {
      error,
      value
    } = joi.validate(ctx.request.query, schema);
    if (error) {
      ctx.status = 201;
      return ctx.body = Res(201, error.toString(), '操作失败');
    }
    console.log('值为：', value);
    const item = await ctx.model.Category.findOne({
      where: {
        id: value.id
      }
    });
    console.log('查找的结果是：', item);
    if (!item) {
      ctx.status = 404;
      return;
    }

    await item.destroy();
    ctx.body = Res(0, item);
  }
}

module.exports = CategoryController;